<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Session;
use app\admin\model\Index as IndexModel;
use app\admin\model\Site as SiteModel;
class Login extends controller
{
	protected $Model;
	public function _initialize()
    {
		$this->config=cache_config();
		if (!Session::has('formcheck')) {
            session('formcheck', get_uniqid());
        }
		$Modelsite=new SiteModel();
		$sitename=$Modelsite->getsitename();
		$this->assign('sitename', $sitename);
        $this->assign('formcheck', session('formcheck'));
		$this->Model=new IndexModel();
	}
    public function index()
    {
		$this->assign('check_code',1);
        return $this->fetch();
    }
	// 异步登录验证
    public function checklog()
    {
		
         if(!$this->request->isPost()){
            return;
        }
        // 在安装了gd库时才执行验证码验证
        if ($this->config['admin_check_code'] && !captcha_check(trim(input('checkcode')))) {
			return json(array('code' =>'0','msg'=>'验证码错误！'));
        }
        //数据
        $username = input('username');
        $password = input('password');
        
        if (! preg_match('/^[\x{4e00}-\x{9fa5}\w\-\.@]+$/u', $username)) {
			return json(array('code' =>'0','msg'=>'用户名含有不允许的特殊字符！'));
        }
        
        if (! $username) {
			return json(array('code' =>'0','msg'=>'用户名不能为空！'));
        }
        
        if (! $password) {
			return json(array('code' =>'0','msg'=>'密码不能为空！'));
        }
        if (! ! $time = $this->checkLoginBlack()) {
			return json(array('code' =>'0','msg'=>'您登录失败次数太多已被锁定，请' . $time . '秒后再试！'));
        }
        // 执行用户登录
        $where = array(
            'username' => $username,
            'password' => encrypt_string($password)
        );
        if ($login = $this->Model->login($where)) {   
            session_regenerate_id(true);
            session('sid', encrypt_string(session_id() . $login['id'])); // 会话标识
            session('id', $login['id']); // 用户id
            session('ucode', $login['ucode']); // 用户编码
            session('username', $login['username']); // 用户名
            session('realname', $login['realname']); // 真实名字
			return json(array('code'=>'1',"msg"=>'success',"data"=> array("url" => url('Index/index'))));
        } else {
            session('checkcode', mt_rand(10000, 99999)); // 登录失败，随机打乱原有验证码
			return json(array('code' =>'0','msg'=>'用户名或密码错误！'));
        }
    }
    //登录验证
    public function logout()
    {
        Session::clear();
        $this->alert('您已安全退出，欢迎您的再次登录','top',url('/index'));
        exit;
    }
		 // 检查是否在黑名单
    private function checkLoginBlack()
    {
        // 读取黑名单
        $ip_black = ROOT_PATH . '/runtime/data/' . md5('login_black') . '.php';
        if (file_exists($ip_black)) {
            $data = require $ip_black;
            $user_ip = get_user_ip();
            $lock_time = $this->config['lock_time'] ?: 900;
            $lock_count = $this->config['lock_count'] ?: 5;
            if (isset($data[$user_ip]) && $data[$user_ip]['count'] >= $lock_count && time() - $data[$user_ip]['time'] < $lock_time) {
                return $lock_time - (time() - $data[$user_ip]['time']); // 返回剩余秒数
            }
        }
        return false;
    }
    /**
     * JS提示跳转
     * @param  $tip  弹窗口提示信息(为空没有提示)
     * @param  $type 设置类型 close = 关闭 ，back=返回 ，refresh=提示重载，jump提示并跳转url
     * @param  $url  跳转url
     */
    function alert($tip = "", $type = "", $url = "") {
        $js="<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
        $js.= "<script>";
        if ($tip)
            $js .= "alert('" . $tip . "');";
        switch ($type) {
            case "close" : //关闭页面
                $js .= "window.close();";
                break;
            case "back" : //返回
                $js .= "history.back(-1);";
                break;
            case "refresh" : //刷新
                $js .= "parent.location.reload();";
                break;
            case "top" : //框架退出
                if ($url)
                    $js .= "top.location.href='" . $url . "';";
                break;
            case "jump" : //跳转
                if ($url)
                    $js .= "window.location.href='" . $url . "';";
                break;
            default :
                break;
        }
        $js .= "</script>";
        echo $js;
        if ($type) {
            exit();
        }
    }
}